<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span style="color: red;">单位：万元
        </span>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag v-model="model.year" placeholder="请选择年度" dictCode="year" @change="handleYearChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="一般公共预算拨款收入" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ybgg">
              <a-input-number v-model="model.ybgg" placeholder="请输入一般公共预算拨款收入" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="国有资本经营预算拨款收入" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gyzb">
              <a-input-number v-model="model.gyzb" placeholder="请输入国有资本经营预算拨款收入" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="事业收入" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sysr">
              <a-input-number v-model="model.sysr" placeholder="请输入事业收入" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="其他收入" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qtsr">
              <a-input-number v-model="model.qtsr" placeholder="请输入其他收入" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="使用非财政拨款结余" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fc">
              <a-input-number v-model="model.fc" placeholder="请输入使用非财政拨款结余" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="一般公共预算结转资金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ybggys">
              <a-input-number v-model="model.ybggys" placeholder="请输入一般公共预算结转资金" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="国有资本经营预算结转资金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gyzbjy">
              <a-input-number v-model="model.gyzbjy" placeholder="请输入国有资本经营预算结转资金" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="其他资金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qtzj">
              <a-input-number v-model="model.qtzj" placeholder="请输入其他资金" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="社会保障和就业支出（离退休经费）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shbz">
              <a-input-number v-model="model.shbz" placeholder="请输入社会保障和就业支出（离退休经费）" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="农业产业发展资金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nycy">
              <a-input-number v-model="model.nycy" placeholder="请输入农业产业发展资金" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="农业经营主体能力提升资金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nyjy">
              <a-input-number v-model="model.nyjy" placeholder="请输入农业经营主体能力提升资金" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="非财项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fcxm">
              <a-input-number v-model="model.fcxm" placeholder="请输入非财项目" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="农村社会事业（中央基建投资）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ncshsy">
              <a-input-number v-model="model.ncshsy" placeholder="请输入农村社会事业（中央基建投资）" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="其他农业农村支出（中央基建投资）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qtnynczc">
              <a-input-number v-model="model.qtnynczc" placeholder="请输入其他农业农村支出（中央基建投资）" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="住房保障支出" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="zfbzzc">
              <a-input-number v-model="model.zfbzzc" placeholder="请输入住房保障支出" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="北大荒农垦改革发展过渡期补助" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nkgg">
              <a-input-number v-model="model.nkgg" placeholder="请输入北大荒农垦改革发展过渡期补助" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="黑龙江垦区社会公益性事务专项经费" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="hlj">
              <a-input-number v-model="model.hlj" placeholder="请输入黑龙江垦区社会公益性事务专项经费" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'CwSzzbForm',
  components: {
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    scene: { // 接收 Modal 传递的场景值
      type: String,
      default: ''
    }
  },
  data() {
    return {
      model: { year: '' }, // 初始为空，由watch同步全局年度
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
      },
      url: {
        add: "/cw/cwSzzb/add",
        edit: "/cw/cwSzzb/edit",
        queryById: "/cw/cwSzzb/queryById",
        queryByYear: "/cw/cwSzzb/queryByYear"
      },
      isManualChange: false // 标记是否手动修改过表单年度
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    ...mapState({ globalYear: state => state.app.globalYear })
  },
  watch: {
    // 监听全局年度变化，同步到表单（仅当未手动修改时）
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
        // 可选：自动触发年度查询，解开注释即可
        // this.handleYearChange(newVal)
      }
    },
    // 监听表单年度变化，标记是否手动修改
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true // 手动修改后，不再同步全局年度
      }
    }
  },
  created() {
    this.model.year = this.globalYear
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    const scene = this.scene; // 接收 Modal 传递的 scene（add/edit）
    this.currentScene = scene; // 存储到本地变量，后续复用
    console.log(scene)
    if (scene=='add'){
      this. handleYearChange(this.model.year)
    }
  },
  methods: {
    add() {
      this.edit(this.modelDefault);
    },
    edit(record) {
      // 重置表单验证状态
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
      });
      this.model = Object.assign({}, record);
      // 确保弹窗可见（如果使用弹窗）
      if (this.hasOwnProperty('visible')) {
        this.visible = true;
      }
    },
    // 年度选择变化处理
    handleYearChange(selectedYear) {
      if (!selectedYear) {
        this.add();
        return;
      }

      this.confirmLoading = true;
      getAction(this.url.queryByYear, { year: selectedYear })
        .then(res => {
          if (res.success) {
            const dataList = res.result; // 后端返回的是List，需取第一个元素
            if (dataList && dataList.length > 0) {
              const data = dataList[0]; // 关键修复：获取列表中第一个数据对象
              this.edit(data); // 进入编辑模式，回显数据
              this.$message.info(`已加载${selectedYear}年度数据，可直接编辑`);
            } else {
              // 无数据，创建新数据
              this.add();
              this.model.year = selectedYear;
              this.$message.info(`未查询到${selectedYear}年度数据，将创建新数据`);
            }
          } else {
            this.add();
            this.$message.error(`查询失败：${res.message}`);
          }
        })
        .catch(err => {
          this.add();
          this.$message.error(`网络异常：${err.message || '请稍后重试'}`);
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
  }
}
</script>